import * as React from 'react';

const { useRef, useState, useEffect } = React;
const VirtualList: React.FC<any> = ({data,
  count,
  size,
  viewSize,
  rowHeight,
  renderNode}) => {
  const scrollRef = useRef();
  const [startIndex, setStartIndex] = useState(0);       // 起始索引
  const [phantomHeight, setPhantomHeight] = useState(0); // 占位区的高度
  const [startOffset, setStartOffset] = useState(0);     // 渲染区域偏移量

  // 计算支撑滚动条区域的高度
  useEffect(() => {
    setPhantomHeight(rowHeight * count);
  }, [count, rowHeight])
/**
   * 滚动时更新显示区域的数据和高度
   * @param {DOM.event} e 
   */
  const onScroll = e => {
    let scrollTop = e.target.scrollTop;               
    let offset = scrollTop - (scrollTop % rowHeight);
    let index = Math.floor(scrollTop / rowHeight); 
    setStartOffset(offset);
    setStartIndex(index);   
  }

  return (
    <div 
      className="jisl-container"
      style={
        (data && data.length > viewSize) || (data && data.length === 0)
        ? { height: rowHeight * viewSize } 
        : { height: rowHeight * data.length }
      }
      onScroll={onScroll}      
    >
      <div className="phantom" style={{height: phantomHeight}} />
      <div 
        className="view"
        style={{transform: `translateY(${startOffset}px)`}}                
      >      
        {
          data instanceof Array && data.length > 0
          ? data.slice(startIndex, startIndex + size).map((item, index) => {
              if(Object.prototype.toString.call(renderNode) !== '[object Function]') return; 
              return renderNode(data, item, index + startIndex);
            })
          : <div />
        }                
      </div>
    </div>
  )
}

export default VirtualList